package in.co.codedoc.sql;

import java.util.HashSet;

@SuppressWarnings("unchecked")
public class SessionLocal<T>
	extends ThreadLocal<T>
{
	@Override
	public T get()
	{
		sessionLocalsHolder.get().add((SessionLocal<Object>)this);
		return super.get();
	}

	@Override
	public void remove()
	{
		sessionLocalsHolder.get().remove((SessionLocal<Object>)this);
		super.remove();
	}

	@Override
	public void set(T value)
	{
		sessionLocalsHolder.get().add((SessionLocal<Object>)this);
		super.set(value);
	}

	public static void ClearAll()
	{
		HashSet<SessionLocal<Object>> sessionLocals = sessionLocalsHolder.get();
		
		for(SessionLocal<Object> sessionLocal:sessionLocals)
		{
			sessionLocal.Clear();
		}
		
		sessionLocals.clear();
	}
	
	public void Clear()
	{
		super.remove();
	}

	private static ThreadLocal<HashSet<SessionLocal<Object>>> sessionLocalsHolder
		= new ThreadLocal<HashSet<SessionLocal<Object>>>()
			{
				@Override
				protected HashSet<SessionLocal<Object>> initialValue()
				{
					return new HashSet<SessionLocal<Object>>();
				}
			
			};
}
